package com.briup.jd2511.jd2511bookstore.interceptor;

import com.briup.jd2511.jd2511bookstore.exception.ServiceException;
import com.briup.jd2511.jd2511bookstore.response.ResultCode;
import com.briup.jd2511.jd2511bookstore.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 日志记录当前拦截的路径
        log.info("当前拦截的url是：{}", request.getRequestURL());
        // 放行预检OPTIONS请求
        if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
            return true;
        }
        // 获取请求头中的token
        String token = request.getHeader("token");
        // 判断token是否存在
        if (!StringUtils.hasText(token)) {
            log.error("token不存在");
            throw new ServiceException(ResultCode.TOKEN_MISSION);
        }
        // 判断token是否有效
        try {
            Claims claims = JwtUtil.parseJWT(token);
            // 如果不放心可以获取claims里面的ID，进行一下查询
            log.info("当前用户id是：{}", claims.get("id"));
        }catch (ExpiredJwtException e){
            log.error("token已过期");
            throw new ServiceException(ResultCode.TOKEN_TIMEOUT);
        }catch (Exception e){
            log.error("token无效");
            throw new ServiceException(ResultCode.TOKEN_IS_INVALID);
        }

        return true;
    }
}
